import VueRouter from "vue-router";
import Vue from "vue";
import routes from '@/router/routes'
import store from "@/store";

Vue.use(VueRouter)

//路由的push方法重复点击会报错，需要重写
//重写push方法
const oldPush = VueRouter.prototype.push
VueRouter.prototype.push = function (location, onComplete = () => {
}, onAbort = () => {
}) {
    return oldPush.call(this, location, onComplete, onAbort)
}
//重写replace方法
const oldReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function (location, onComplete = () => {
}, onAbort = () => {
}) {
    return oldReplace.call(this, location, onComplete, onAbort)
}

const router = new VueRouter({
    mode: 'history',
    routes,
    scrollBehavior(to, from, savedPosition) {
        //跳转到每个路由时会置顶
        return {x: 0, y: 0}
    }
})

//使用全局前置守卫来做路由权限限制
router.beforeEach(async (to, from, next) => {
    const token = store.state.user.token
    const whitePath = ['Login', 'Register', 'AddCartSuccess', 'Home', 'Search',
        'Detail', 'ShopCart']
    if (token) {
        if (to.name === 'Login') {
            next('/home')
        } else {
            const userInfo = !!store.state.user.userInfo.nickName
            if (userInfo) {
                next()
            } else {
                try {
                    await store.dispatch('user/getUserInfo')
                    next()
                } catch (e) {
                    store.dispatch('user/resetUserInfo')
                    next(`/login?redirect=${to.name}`)
                }
            }
        }
    } else {
        if (whitePath.includes(to.name)) {
            next()
        } else {
            next(`/login?redirect=${to.name}`)
        }
    }
})

export default router